<template>
    <div class="groups-list">
        <div class="groups-header">
            <h3>Groups</h3>
            <van-button size="small" type="primary" @click="showCreateGroup">
                <van-icon name="plus" />
                Create Group
            </van-button>
        </div>

        <!-- 搜索和筛选 -->
        <div class="search-section">
            <van-search v-model="searchQuery" placeholder="Search groups..." @search="handleSearch"
                @clear="handleClearSearch" />
            <div class="filter-tabs">
                <van-tabs v-model:active="activeFilter" @change="handleFilterChange">
                    <van-tab title="All" name="all" />
                    <van-tab title="Joined" name="joined" />
                    <van-tab title="Popular" name="popular" />
                    <van-tab title="New" name="new" />
                </van-tabs>
            </div>
        </div>

        <!-- 推荐群组 -->
        <div v-if="activeFilter === 'all' && recommendedGroups.length > 0" class="recommended-section">
            <h4>Recommended for You</h4>
            <div class="recommended-groups">
                <div v-for="group in recommendedGroups" :key="group.id" class="recommended-group"
                    @click="viewGroup(group)">
                    <van-image :src="group.avatar || '/default-group.png'" width="60" height="60" round fit="cover" />
                    <div class="group-info">
                        <div class="group-name">{{ group.name }}</div>
                        <div class="group-stats">
                            <span>{{ group.members_count }} members</span>
                        </div>
                    </div>
                    <van-button size="small" type="primary" @click.stop="joinGroup(group)">
                        Join
                    </van-button>
                </div>
            </div>
        </div>

        <!-- 群组列表 -->
        <div class="groups-content">
            <van-loading v-if="loading" size="24px" vertical>Loading groups...</van-loading>
            <div v-else-if="filteredGroups.length > 0" class="groups-grid">
                <div v-for="group in filteredGroups" :key="group.id" class="group-card"
                    :class="{ joined: group.is_joined }" @click="viewGroup(group)">
                    <!-- 群组头像和状态 -->
                    <div class="group-header">
                        <div class="group-avatar">
                            <van-image :src="group.avatar || '/default-group.png'" width="48" height="48" round
                                fit="cover" />
                            <div v-if="group.is_private" class="private-badge">
                                <van-icon name="lock" />
                            </div>
                            <div v-if="group.is_verified" class="verified-badge">
                                <van-icon name="success" />
                            </div>
                        </div>
                        <div v-if="group.is_joined" class="joined-indicator">
                            <van-icon name="success" />
                        </div>
                    </div>

                    <!-- 群组信息 -->
                    <div class="group-info">
                        <h4 class="group-name">{{ group.name }}</h4>
                        <p class="group-description">{{ group.description }}</p>

                        <!-- 群组标签 -->
                        <div v-if="group.tags && group.tags.length > 0" class="group-tags">
                            <van-tag v-for="tag in group.tags.slice(0, 2)" :key="tag" type="primary" plain>
                                {{ tag }}
                            </van-tag>
                            <span v-if="group.tags.length > 2" class="more-tags">
                                +{{ group.tags.length - 2 }}
                            </span>
                        </div>

                        <!-- 群组统计 -->
                        <div class="group-stats">
                            <div class="stat-item">
                                <van-icon name="friends-o" />
                                <span>{{ formatNumber(group.members_count) }}</span>
                            </div>
                            <div class="stat-item">
                                <van-icon name="chat-o" />
                                <span>{{ formatNumber(group.posts_count) }}</span>
                            </div>
                            <div class="stat-item">
                                <van-icon name="fire-o" />
                                <span>{{ group.activity_level }}</span>
                            </div>
                        </div>

                        <!-- 最新活动 -->
                        <div v-if="group.latest_activity" class="latest-activity">
                            <span class="activity-text">{{ group.latest_activity.text }}</span>
                            <span class="activity-time">{{ formatTime(group.latest_activity.time) }}</span>
                        </div>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="group-actions">
                        <van-button v-if="!group.is_joined" size="small" type="primary" @click.stop="joinGroup(group)"
                            :loading="group.joining">
                            {{ group.is_private ? 'Request' : 'Join' }}
                        </van-button>
                        <van-button v-else size="small" @click.stop="viewGroup(group)">
                            View
                        </van-button>
                    </div>
                </div>
            </div>
            <van-empty v-else description="No groups found" image="search">
                <van-button type="primary" @click="showCreateGroup">
                    Create First Group
                </van-button>
            </van-empty>
        </div>

        <!-- 创建群组弹窗 -->
        <van-popup v-model:show="showCreateGroupPopup" position="bottom" :style="{ height: '70%' }" round>
            <CreateGroupModal v-if="showCreateGroupPopup" @submit="handleCreateGroup"
                @close="showCreateGroupPopup = false" />
        </van-popup>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { showToast } from 'vant'
import type { CommunityGroup } from '@/types/community'
import CreateGroupModal from '@/components/CreateGroupModal.vue'

interface Props {
    groups: CommunityGroup[]
}

const props = defineProps<Props>()

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const activeFilter = ref('all')
const showCreateGroupPopup = ref(false)

// 模拟推荐群组数据
const recommendedGroups = ref<CommunityGroup[]>([
    {
        id: 101,
        name: 'Communication Skills',
        avatar: '/group-communication.png',
        members_count: 1250,
        is_joined: false
    } as CommunityGroup,
    {
        id: 102,
        name: 'Leadership Training',
        avatar: '/group-leadership.png',
        members_count: 890,
        is_joined: false
    } as CommunityGroup
])

// 计算属性
const filteredGroups = computed(() => {
    let filtered = props.groups

    // 搜索过滤
    if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        filtered = filtered.filter(group =>
            group.name.toLowerCase().includes(query) ||
            group.description?.toLowerCase().includes(query)
        )
    }

    // 分类过滤
    switch (activeFilter.value) {
        case 'joined':
            filtered = filtered.filter(group => group.is_joined)
            break
        case 'popular':
            filtered = filtered.sort((a, b) => (b.members_count || 0) - (a.members_count || 0))
            break
        case 'new':
            filtered = filtered.sort((a, b) =>
                new Date(b.created_at || '').getTime() - new Date(a.created_at || '').getTime()
            )
            break
    }

    return filtered
})

// 方法
const formatNumber = (num: number) => {
    if (num >= 1000) {
        return `${(num / 1000).toFixed(1)}k`
    }
    return num.toString()
}

const formatTime = (timestamp: string) => {
    const now = new Date()
    const time = new Date(timestamp)
    const diffInHours = Math.floor((now.getTime() - time.getTime()) / (1000 * 60 * 60))

    if (diffInHours < 1) {
        return 'Just now'
    } else if (diffInHours < 24) {
        return `${diffInHours}h ago`
    } else {
        const days = Math.floor(diffInHours / 24)
        return `${days}d ago`
    }
}

const handleSearch = (value: string) => {
    searchQuery.value = value
}

const handleClearSearch = () => {
    searchQuery.value = ''
}

const handleFilterChange = () => {
    loading.value = true
    setTimeout(() => {
        loading.value = false
    }, 300)
}

const viewGroup = (group: CommunityGroup) => {
    showToast(`Viewing ${group.name}`)
}

const joinGroup = async (group: CommunityGroup) => {
    try {
        group.joining = true
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))

        group.is_joined = true
        group.members_count = (group.members_count || 0) + 1

        showToast(group.is_private ? 'Join request sent!' : 'Joined successfully!')
    } catch (error) {
        console.error('Failed to join group:', error)
        showToast('Failed to join group')
    } finally {
        group.joining = false
    }
}

const showCreateGroup = () => {
    showCreateGroupPopup.value = true
}

const handleCreateGroup = async () => {
    try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))

        showCreateGroupPopup.value = false
        showToast('Group created successfully!')
    } catch (error) {
        console.error('Failed to create group:', error)
        showToast('Failed to create group')
    }
}

// 生命周期
onMounted(() => {
    // 初始化数据
})
</script>

<style lang="scss" scoped>
.groups-list {
    .groups-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        h3 {
            font-size: 20px;
            font-weight: 600;
            color: #323233;
            margin: 0;
        }
    }

    .search-section {
        margin-bottom: 20px;

        .van-search {
            background: white;
            border-radius: 12px;
            margin-bottom: 12px;
        }

        .filter-tabs {
            :deep(.van-tabs) {
                .van-tab {
                    font-size: 14px;
                    padding: 8px 16px;
                }
            }
        }
    }

    .recommended-section {
        margin-bottom: 24px;

        h4 {
            font-size: 16px;
            font-weight: 600;
            color: #323233;
            margin: 0 0 12px 0;
        }

        .recommended-groups {
            display: flex;
            gap: 12px;
            overflow-x: auto;
            padding-bottom: 8px;

            .recommended-group {
                display: flex;
                flex-direction: column;
                align-items: center;
                padding: 12px;
                background: white;
                border-radius: 12px;
                min-width: 120px;
                cursor: pointer;
                transition: transform 0.3s ease;

                &:hover {
                    transform: translateY(-2px);
                }

                .group-info {
                    text-align: center;
                    margin: 8px 0;

                    .group-name {
                        font-size: 13px;
                        font-weight: 500;
                        color: #323233;
                        margin-bottom: 4px;
                    }

                    .group-stats {
                        font-size: 11px;
                        color: #969799;
                    }
                }
            }
        }
    }

    .groups-content {
        .groups-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 16px;

            .group-card {
                background: white;
                border-radius: 12px;
                padding: 16px;
                cursor: pointer;
                transition: all 0.3s ease;
                border: 2px solid transparent;

                &:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
                }

                &.joined {
                    border-color: #07c160;
                    background: linear-gradient(135deg, #f0f9ff, #e0f7fa);
                }

                .group-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: flex-start;
                    margin-bottom: 12px;

                    .group-avatar {
                        position: relative;

                        .private-badge {
                            position: absolute;
                            top: -4px;
                            right: -4px;
                            width: 16px;
                            height: 16px;
                            background: #ee0a24;
                            border-radius: 50%;
                            display: flex;
                            align-items: center;
                            justify-content: center;

                            .van-icon {
                                color: white;
                                font-size: 10px;
                            }
                        }

                        .verified-badge {
                            position: absolute;
                            bottom: -4px;
                            right: -4px;
                            width: 16px;
                            height: 16px;
                            background: #07c160;
                            border-radius: 50%;
                            display: flex;
                            align-items: center;
                            justify-content: center;

                            .van-icon {
                                color: white;
                                font-size: 10px;
                            }
                        }
                    }

                    .joined-indicator {
                        .van-icon {
                            color: #07c160;
                            font-size: 20px;
                        }
                    }
                }

                .group-info {
                    margin-bottom: 16px;

                    .group-name {
                        font-size: 16px;
                        font-weight: 600;
                        color: #323233;
                        margin: 0 0 6px 0;
                    }

                    .group-description {
                        font-size: 14px;
                        color: #646566;
                        line-height: 1.4;
                        margin: 0 0 12px 0;
                        display: -webkit-box;
                        -webkit-line-clamp: 2;
                        line-clamp: 2;
                        -webkit-box-orient: vertical;
                        overflow: hidden;
                    }

                    .group-tags {
                        display: flex;
                        align-items: center;
                        gap: 6px;
                        margin-bottom: 12px;

                        .more-tags {
                            font-size: 12px;
                            color: #969799;
                        }
                    }

                    .group-stats {
                        display: flex;
                        gap: 16px;
                        margin-bottom: 8px;

                        .stat-item {
                            display: flex;
                            align-items: center;
                            gap: 4px;
                            font-size: 12px;
                            color: #646566;

                            .van-icon {
                                color: #1989fa;
                                font-size: 14px;
                            }
                        }
                    }

                    .latest-activity {
                        font-size: 12px;
                        color: #969799;

                        .activity-text {
                            margin-right: 8px;
                        }

                        .activity-time {
                            font-weight: 500;
                        }
                    }
                }

                .group-actions {
                    display: flex;
                    justify-content: flex-end;

                    .van-button {
                        min-width: 80px;
                    }
                }
            }
        }
    }
}
</style>